import socket
import time
from concurrent.futures import ThreadPoolExecutor
from Utils import *
from CmdMappingFun import *
import Config


MaxClient = 2 # 同时链接最大客户端数量
MaxRequest = 3 # 同时处理最多请求数量
pool = ThreadPoolExecutor(MaxRequest)

# 处理请求，错误直接返回空
def ProcessingRequest(funID, data):
    reply = ""
    tfunc = GetFun(NetworkCMD(funID))

    if tfunc == None :
        print("错误！服务器不存在处理方法" + NetworkCMD(funID))
        return "error"
    reply = tfunc(data)
    reply = Dict2str(reply)
    print("返回数据" + reply)
    return reply

# 重新封装数据
def PackagedData(cetworkCMD, data):
    
    responseData = {"ID": cetworkCMD, "msg": data}  # 重新封装数据
    return responseData


def HandleClient(client_socket, addr):
    print('已连接 {}:{}'.format(addr[0],addr[1]))
    # 接收客户端请求
    request = client_socket.recv(1024 * 1024)
    jdata = Deserialization(request)
    print('收到消息 {}:{} :{}'.format(addr[0],addr[1],jdata))
    curCMDID = jdata["ID"]
    curCMDMSG = jdata["msg"]

    # 把数据丢给方法处理，处理完毕后返回消息，不管有没有都要返回
    responseData = ProcessingRequest(curCMDID, curCMDMSG)
    if responseData == "error" :
        client_socket.close()
        return
    
    packagedData = PackagedData(curCMDID, responseData)# 重新封装数据

    print("处理完毕, 返回" + str(packagedData))
    client_socket.send(Serialization(packagedData))
    client_socket.close()



def RunServer():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_socket.bind((Config.curIP, Config.Port))
    server_socket.listen(MaxClient)
    print("服务器已启动..." + str(Config.curIP) + " " +  str(Config.Port )) 

    while True:
        client_socket, addr = server_socket.accept()
        future = pool.submit(HandleClient, client_socket, addr)
        try:
            result = future.result()
        except Exception as e:
            print('>>> main ThreadPoolExecutor, e: ', e.args)

if __name__ == '__main__':
    RunServer()
